//
//  StringExt.swift
//  covermedia
//
//  Created by Travel on 16/1/22.
//  Copyright © 2016年 covermedia. All rights reserved.
//

import Foundation
import UIKit
import CryptoSwift

public extension String  {
    public var md5: String! {
        return self.md5().uppercased()
    }
    
    public func cm_Images() -> [String] {
        return self.components(separatedBy: ";").flatMap({ !$0.isEmpty ? $0 : nil })
    }
    
    public func limitLength(_ maxLength:Int = 120, replace:String = ".") -> String {
        let length = self.characters.count
        if length > maxLength && maxLength > 0 {
            let replaceLength = replace.characters.count
            if maxLength > replaceLength {
                return self.substring(to: self.characters.index(self.startIndex, offsetBy: maxLength - replaceLength)) + replace
            }
            return replace.substring(to: replace.characters.index(replace.startIndex, offsetBy: maxLength))
        }
        return self
    }
    
    //计算字串高度
    public func height(_ space:CGFloat,fsize:CMFontSize,lwidth:CGFloat) -> CGFloat {
        return NSString.init(string: self).boundingRect(with: CGSize(width: lwidth, height: 100000),
                                                                     options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                                                  attributes: attributes(space, fsize: fsize,color:UIColor.white),
                                                                     context: nil).height
    }
    
    public func attributes(_ space:CGFloat,fsize:CMFontSize,color:UIColor) -> [String : AnyObject] {
        let style = NSMutableParagraphStyle()
        style.lineSpacing = space
        let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: fsize.fontSize),
                          NSParagraphStyleAttributeName: style,
                          NSForegroundColorAttributeName: color
        ]
        return attributes
    }
}

public extension String {
    
    public var isValidCellPhone: Bool {
        let string: NSString = NSString(string: self)
        let mobile = "^1\\d{10}$"
//        let  CM = "^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$"
//        let  CU = "^1(3[0-2]|5[256]|8[56])\\d{8}$"
//        let  CT = "^1((33|53|8[09])[0-9]|349)\\d{7}$"
        let regextestmobile = NSPredicate(format: "SELF MATCHES %@",mobile)
//        let regextestcm = NSPredicate(format: "SELF MATCHES %@",CM )
//        let regextestcu = NSPredicate(format: "SELF MATCHES %@" ,CU)
//        let regextestct = NSPredicate(format: "SELF MATCHES %@" ,CT)
        if (regextestmobile.evaluate(with: string) == true)
//            || (regextestcm.evaluateWithObject(string)  == true)
//            || (regextestct.evaluateWithObject(string) == true)
//            || (regextestcu.evaluateWithObject(string) == true))
        {
            return true
        } else
        {
            return false
        }
    }
}

public extension String {
    public var isValidPassword: Bool {
        return self =~ "^[a-zA-Z0-9]{6,16}$"
    }
    public var isHan: Bool {
        return self =~ "^[\\u4e00-\\u9fa5]{0,}$"
    }
    
    public var isValidName: Bool {
        return self =~ "^[a-zA-Z0-9\\u4e00-\\u9fa5]+$"
    }
}

public struct RegexHelper {
    public let regex: NSRegularExpression
    public init(_ pattern: String) throws {
        try regex = NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
    }
    public func match(_ input: String) -> Bool {
        let matches = regex.matches(in: input, options: [], range: NSMakeRange(0, input.characters.count))
        return matches.count > 0
    }
}

infix operator =~ : RegexPrecedence

precedencegroup RegexPrecedence {
    associativity: left
    lowerThan: AdditionPrecedence
}

func =~ (lhs: String, rhs: String) -> Bool {
    do {
        return try RegexHelper(rhs).match(lhs)
    } catch _ {
        return false
    }
}

public extension String {
    public var cmSingleLine:String {
        return self.replacingOccurrences(of: "\n", with: "")
    }
}


public extension String {
    public var jsonStringToDictionary: [String: Any]? {
        if let data = self.data(using: String.Encoding.utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
            } catch let error as NSError {
                cmlog(error, level: .error)
            }
        }
        return nil
    }
}

